﻿using PermissionManager.Model;
using PermissionsManager.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PermissionManager.BLL
{
    public class RoleApIService : BaseService<Role>
    {
        /// <summary>
        /// 获取用户下的菜单权限
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public UserRoleFunction GetUserRoleFunction(int userid)
        {
            UserRoleFunction userRoleFunction = new UserRoleFunction();

            using (var db = new PermissionManagerEntities())
            {
                //获取用户关联的角色
                var result = from a in db.AdminUser
                             join b in db.AdminUserRole
                             on a.Id equals b.AdminUserId
                             join c in db.Role
                             on b.RoleId equals c.Id
                             where a.Id == userid
                             select new UserRoleFunction()
                             {
                                 AdminUserId = a.Id,
                                 RoleId = c.Id,
                                 RoleName = c.Name
                             };
                var userRole = result.FirstOrDefault();

                userRoleFunction.AdminUserId = userRole.AdminUserId;
                userRoleFunction.RoleId = userRole.RoleId;
                userRoleFunction.RoleName = userRole.RoleName;

                //获取用户关联了哪些菜单
                //二级菜单
                var menu = from a in result
                           join c in db.RoleFunctionPermission
                           on a.RoleId equals c.RoleId
                           join e in db.Menu
                           on c.MenuId equals e.Id                           
                           select e;
                var childMenus = menu.Distinct().ToList();

                //获取菜单对应的功能
                List<MenuFunction> menuFunctions = new List<MenuFunction>();
                foreach (var item in childMenus)
                {
                    MenuFunction menuFunction = new MenuFunction();
                    menuFunction.MenuId = item.Id;
                    menuFunction.MenuName = item.Name;
                    menuFunction.ParentId = item.ParentId;
                    menuFunction.Functions = db.Function.Where(a => a.MenuId == item.Id).ToList();
                    menuFunctions.Add(menuFunction);
                }

                userRoleFunction.MenuFunctions = menuFunctions;
            }

            return userRoleFunction;
        }
    }
}
